package com.newfiber.workflow.support.page.scope;

import cn.hutool.core.util.XmlUtil;
import com.newfiber.workflow.enums.EQueryScope;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 * @author : X.K
 * @since : 2022/6/20 下午3:45
 */
public class QueryScopeUtil {

	private static final List<QueryScopeCondition> QUERY_SCOPE_CONDITION_LIST = new ArrayList<>();{
		InputStream inputStream = Objects.requireNonNull(
			Thread.currentThread().getContextClassLoader()
				.getResourceAsStream("JoinTableTemplate"));
		Document document = XmlUtil.readXML(inputStream);

		Element rootElement = XmlUtil.getRootElement(document);

		List<Element> templateElementList = XmlUtil.getElements(rootElement, "template");

		for(EQueryScope queryScope : EQueryScope.values()){
			Optional<Element> elementOptional = templateElementList.stream().filter(t -> t.getAttribute("id").equals(queryScope.name())).findAny();
			if(elementOptional.isPresent()){
				Element templateElement = elementOptional.get();

				Element joinConditionElement = XmlUtil.getElement(templateElement, "joinCondition");
				Element userConditionElement = XmlUtil.getElement(templateElement, "userCondition");
				Element groupConditionElement = XmlUtil.getElement(templateElement, "groupCondition");

				QUERY_SCOPE_CONDITION_LIST.add(new QueryScopeCondition(queryScope.name(), joinConditionElement,
					userConditionElement, groupConditionElement));
			}
		}

	}

	public static QueryScopeCondition match(EQueryScope queryScope){
		Optional<QueryScopeCondition> conditionOptional = QUERY_SCOPE_CONDITION_LIST.stream().filter(t -> t.getScopeId().equals(queryScope.name())).findAny();
		return conditionOptional.orElse(null);
	}

}
